<?php

namespace Ignus\View\Node\Expression;

use Ignus\View\Node\Expression;
use Ignus\View\Compiler;
use Ignus\View\Node;
use Ignus\View\NodeInterface;

class GetAttr extends Expression
{
    public function __construct(Expression $node, Expression $attribute, NodeInterface $arguments, $type, $lineno)
    {
        $nodes = array(
            'node'      => $node,
            'attribute' => $attribute,
            'arguments' => $arguments
        );
        parent::__construct($nodes, array('type' => $type), $lineno);
    }

    public function compile(Compiler $compiler)
    {
        $compiler->raw('$this->getAttribute(');

        if ($this->hasAttribute('is_defined_test') && $compiler->getEnvironment()->isDebug()) {
            $compiler->subcompile(new Filter(
                $this->getNode('node'),
                new Constant('default', $this->getLine()),
                new Node(),
                $this->getLine()
            ));
        }
        else {
            $compiler->subcompile($this->getNode('node'));
        }

        $compiler
            ->raw(', ')
            ->subcompile($this->getNode('attribute'))
            ->raw(', array(');

        foreach ($this->getNode('arguments') as $node) {
            $compiler->subcompile($node)->raw(', ');
        }

        $compiler
            ->raw('), ')
            ->repr($this->getAttribute('type'))
            ->raw($this->hasAttribute('is_defined_test') ? ', true' : ', false')
            ->raw(')');
    }
}
